<?php
/**
 * Description: 新品速递-列表
 * Created by PhpStorm.
 * User: congyukun
 * Date: 2021/5/19
 * Time: 15:34
 */

use Biz\cache\wiki\GoodsHot;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\service\NewProduct\NewProductService;
use Biz\tools\helper\Common;
use Doraemon\model\Member;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\tools\HhzClient;
use Hhzbeads\Img\ImgUrl;


class ListAction extends ActionPlugin
{
    public const USER_LEVEL = self::LEVEL_NOTHING;
    public const SCORLL_NUM = 10;
    public const VALIDATOR_RULES = [
        'type' => 'require|integer',
        'page' => 'require|integer',
    ];

    /**
     * @type 1：超级新品  2：甄选新品
     * @throws Exception
     */
    public function main()
    {
        $uid = $this->uid ?? 0;
        //查询符合展示时间的wiki
        $type = $this->params['type'];
        $page = $this->params['page'];
        $per_page = $this->params['per_page'] ?? 10;
        //初始化
        $data = [
            'is_over' => 1,
            'current_page' => $page,
            'list' => [],
        ];
        $where['type'] = NewProductWikiModel::GRACE_PDT;
        if ((int)$type === NewProductWikiModel::SUPER_PDT) {
            $where['type'] = NewProductWikiModel::SUPER_PDT;
            $per_page = 15;
            $where['ORDER'] = [
                'sort' => "DESC",
                'start_time' => 'DESC',
                'create_time' => 'DESC',
            ];
        }
        //获取 想要的字段
        $field = [
            'id',
            'brand_name',
            'basic_id',
            'wiki_id',
            'img',
            'name',
            'desc',
            'features',
            'type',
            'start_time',
            'end_time',
            'question',
            'brand_id',
        ];
        //偏移量，当前页-1乘以每页显示条数
        $start = ($page - 1) * $per_page;
        //获取活动商品列表
        $list = NewProductService::getNewProductInfo($where, $field, $start, $per_page) ?? [];
        if ((int)$type === NewProductWikiModel::GRACE_PDT) {
            $list = $this->_formatByHot($list);
        }
        if (!$list) {
            return $this->setSuccess($data);
        }
        $list = $this->_isFav($uid, $list);
        $list = $this->_isLike($uid, $list, $type);
        $ids = array_column($list, 'id');
        $list = $this->_format($list, $ids, $type, $uid);
        $is_over = 0;
        if (count($list) < $per_page) {
            $is_over = 1;
        }

        $data['list'] = $list;
        $data['is_over'] = $is_over;
        $data['current_page'] = $page;
        return $this->setSuccess($data);

    }

    /**
     * 按照热度排序
     * @param $list
     * @return mixed
     */
    private function _formatByHot($list)
    {
        $basic_ids = array_column($list, 'basic_id');
        $cache_hots = GoodsHot::getMulti($basic_ids);
        $cache_ids = array_keys($cache_hots);
        foreach ($list as $k => $item) {
            if (in_array($item['basic_id'], $cache_ids)) {
                $list[$k]['hot'] = $cache_hots[$item['basic_id']] ?? 0;
            }
        }

//       $list = Common::sortArrayByField($list,'hot','desc');
        //取热度
        $hots = array_column($list, 'hot');
        //按照热度排序hots
        array_multisort($hots, SORT_DESC, $list);
        return $list;
    }

    /**
     * @param $list
     * @param $ids
     * @param $type
     * @param $uid
     * @return array
     */
    private function _format($list, $ids, $type, $uid): array
    {
        //获取标签列表
        $tag_list = NewProductService::getTagsByNid($ids);
        if (!$tag_list) {
            return [];
        }
        $new_tag_list = [];
        foreach ($tag_list as $item) {
            $new_tag_list[$item['nid']][] = $item ?? [];
        }
        $back_imgs = [
            'http://img.hhz1.cn/Op-imageShow/c924630t61250dW00qtnson?iv=1',
            'http://img.hhz1.cn/Op-imageShow/6f7b730t612504v00qtnsox?iv=1',
            'http://img.hhz1.cn/Op-imageShow/7cda130t61250l400qtnsp6?iv=1',
            'http://img.hhz1.cn/Op-imageShow/9c17830t61250RG00qtnspg?iv=1',
        ];
        //数据处理
        foreach ($list as $k => &$value) {
            if (isset($new_tag_list[$value['id']])) {
                $value['tag'] = $new_tag_list[$value['id']];
            }
            if (isset($value['features']) && $value['features']) {
                $value['features'] = explode(',', $value['features']);
            }
            if (isset($value['img']) && $value['img']) {
                $value['img'] = ImgUrl::getUrlNoWater(ImgUrl::APPTYPE_BIZ, $value['img'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
            }
            //滚动条数据
            if ((int)$type === NewProductWikiModel::GRACE_PDT) {
                $scroll_logs = $this->_getScrollRecords($value['id'], $new_tag_list[$value['id']]) ?? [];
                $value['scroll_list'] = $scroll_logs;
            }
            //超级新品背景
            if ((int)$type === NewProductWikiModel::SUPER_PDT) {
                $value['back_img'] = $back_imgs[$k % count($back_imgs)];
            }
            //埋点
            $value['statSign'] = basicStatSign::genStatSign(basicStatSign::MODULE_NEW_PRODUCT_WIKI_LIST, [
                basicStatSign::EXTEND_KEY_OBJ_TYPE => \Doraemon\tools\BlockType::TYPE_WIKI,
                basicStatSign::EXTEND_KEY_OBJ_ID => $value['wiki_id']
            ],
                [
                    'uid' => $uid,
                    'wiki_id' => $value['wiki_id'],
                    'basic_id' => $value['basic_id'],
                    'act_from' => 'new_product'
                ]);

        }
        return $list;
    }

    /**
     * 获取滚动条数据
     * @param $id
     * @param $tags
     * @return array
     */
    private function _getScrollRecords($id, $tags)
    {

        //查询 参与的全部记录
        $logs = NewProductService::getJoinRecord($id);
        $new_uids = $logs ? array_column($logs, 'uid') : [];

        //获取机器人 uid集合
        $uids = Common::getMechanicUids();
        //获取机器人
        $num = self::SCORLL_NUM;
        if ($logs) {
            $account = count($logs);
            if ($account < self::SCORLL_NUM) {
                $num = self::SCORLL_NUM - $account;
                //获取机器人uid集合
            }
        }

        $rand_uids = [];
        if ($num !== 0) {
            $rand_uid_keys = array_rand($uids, $num);
            foreach ($rand_uid_keys as $key) {
                $rand_uids[] = $uids[$key];
            }
        }
        $new_uids = array_merge($new_uids, $rand_uids);
        //获取用户信息
        $memberList = Member::getUserInfoByIds(array_unique($new_uids));

        $memberList = array_column($memberList, null, 'uid');
        //增加用户名称
        foreach ($logs as &$log) {
            $log['nick'] = $memberList[$log['uid']]['nick'] ?? '';
        }
        //添加假数据
        $new_logs = [];
        foreach ($memberList as $key => $item) {
            $tag_key = array_rand($tags, 1);
            $new_logs[$key]['nick'] = $item['nick'];
            $new_logs[$key]['tag'] = $tags[$tag_key]['tag'];
            $new_logs[$key]['nid'] = $id;
            $new_logs[$key]['uid'] = $item['uid'];
            $new_logs[$key]['tid'] = $tags[$tag_key]['id'];
        }
        return array_merge($logs, $new_logs);
    }

    /**
     * 获取是否收藏
     * @param $uid
     * @param $list
     * @return mixed
     * @throws Exception
     */
    private function _isFav($uid, $list)
    {
        $appSource = 0;
        if (HhzClient::getClientType() == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            $appSource = HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM;
        } elseif (HhzClient::getClientType() === HhzClient::APPTYPE_DESIGNER_FUNENG_MINIPROGRAM) {
            $appSource = HhzClient::APPTYPE_DESIGNER_FUNENG_MINIPROGRAM;
        }
        $wiki_ids = array_column($list, 'wiki_id');
        $isFavList = $wiki_ids ? mShopFavorite::is_favorited($uid, $wiki_ids, mShopFavorite::TYPE_WIKI,
            $appSource) : [];
        foreach ($list as $k => $v) {
            $list[$k]['is_fav'] = $isFavList[$v['wiki_id']] ?? 0;
        }
        return $list;
    }

    /**
     * 获取用户是否喜欢
     * @param $uid
     * @param $list
     * @param $type
     * @return mixed
     */
    private function _isLike($uid, $list, $type)
    {
        $ids = array_column($list, 'id');

        $info = NewProductService::getUserIsLike($ids, $uid, $type);

        $info = array_column($info, 'uid', 'nid');

        foreach ($list as $k => $v) {
            $list[$k]['is_like'] = $info[$v['id']] ? 1 : 0;
        }
        return $list;
    }


}
